//! Actix-web 使用示例
//! 展示如何在 Actix-web 中使用 unified_api 框架

#[cfg(feature = "actix")]
mod actix_impl {
    use actix_web::{get, post, web, App, HttpServer, HttpResponse, Result};
    use serde::{Deserialize, Serialize};
    use unified_api::{
        auth::{JwtAuthPolicy, AuthPolicy, AuthContext, AuthRequest, AuthResult},
        routers::{RouteInfo, RouteBuilder}
    };

    #[derive(Debug, Serialize, Deserialize)]
    struct User {
        id: u64,
        name: String,
        email: String,
    }

    #[derive(Debug, Serialize, Deserialize)]
    struct CreateUserRequest {
        name: String,
        email: String,
    }

    // 使用 Actix-web 的原生属性宏 + unified_api 的路由配置
    #[get("/users")]
    async fn get_users() -> Result<HttpResponse> {
        let users = vec![
            User {
                id: 1,
                name: "Alice".to_string(),
                email: "alice@example.com".to_string(),
            },
            User {
                id: 2,
                name: "Bob".to_string(),
                email: "bob@example.com".to_string(),
            },
        ];

        Ok(HttpResponse::Ok().json(serde_json::json!({
            "users": users,
            "total": users.len()
        })))
    }

    #[get("/users/{id}")]
    async fn get_user_by_id(path: web::Path<u64>) -> Result<HttpResponse> {
        let id = path.into_inner();
        
        if id == 1 {
            let user = User {
                id: 1,
                name: "Alice".to_string(),
                email: "alice@example.com".to_string(),
            };
            Ok(HttpResponse::Ok().json(user))
        } else {
            Ok(HttpResponse::NotFound().json(serde_json::json!({
                "error": "User not found"
            })))
        }
    }

    #[post("/users")]
    async fn create_user(
        user_data: web::Json<CreateUserRequest>
    ) -> Result<HttpResponse> {
        let user = User {
            id: 3,
            name: user_data.name.clone(),
            email: user_data.email.clone(),
        };

        Ok(HttpResponse::Created().json(serde_json::json!({
            "message": "User created successfully",
            "user": user
        })))
    }

    #[get("/health")]
    async fn health_check() -> Result<HttpResponse> {
        Ok(HttpResponse::Ok().json(serde_json::json!({
            "status": "healthy",
            "timestamp": chrono::Utc::now().to_rfc3339()
        })))
    }

    // 自定义认证中间件
    async fn auth_middleware(
        req: actix_web::HttpRequest,
        next: actix_web::dev::ServiceRequest,
    ) -> Result<actix_web::dev::ServiceResponse, actix_web::Error> {
        // 这里可以集成 unified_api 的认证策略
        // 目前简化实现
        
        if req.path() == "/api/health" {
            // 健康检查不需要认证
            return next.call(req).map(|res| res.map_into_right_body()).await;
        }

        // 检查 Authorization header
        if let Some(auth_header) = req.headers().get("Authorization") {
            if let Ok(auth_str) = auth_header.to_str() {
                if auth_str.starts_with("Bearer ") {
                    let token = &auth_str[7..];
                    if token == "valid-token" {
                        return next.call(req).map(|res| res.map_into_right_body()).await;
                    }
                }
            }
        }

        Ok(actix_web::dev::ServiceResponse::new(
            req.into_parts().0,
            HttpResponse::Unauthorized().json(serde_json::json!({
                "error": "Unauthorized"
            })).into_body().into(),
        ))
    }

    #[actix_web::main]
    pub async fn main() -> std::io::Result<()> {
        println!("Starting Actix-web server with unified_api framework");

        // 使用 unified_api 创建路由配置
        let routes = vec![
            RouteInfo::new("/api/users", "GET", "get_users")
                .with_auth_policy("permission:users.read")
                .with_description("获取所有用户列表")
                .with_tags(vec!["users", "admin"]),
                
            RouteInfo::new("/api/users/{id}", "GET", "get_user_by_id")
                .with_auth_policy("permission:users.read")
                .with_description("根据ID获取用户信息")
                .with_tags(vec!["users"]),
                
            RouteInfo::new("/api/users", "POST", "create_user")
                .with_auth_policy("permission:users.create")
                .with_description("创建新用户")
                .with_tags(vec!["users", "admin"]),
                
            RouteInfo::new("/api/health", "GET", "health_check")
                .with_auth_policy("") // 不需要认证
                .with_description("健康检查接口")
                .with_tags(vec!["health"]),
        ];

        println!("Configured {} routes:", routes.len());
        for (i, route) in routes.iter().enumerate() {
            println!("  {}. {} {} - {}", i + 1, route.method, route.path, 
                     route.description.as_deref().unwrap_or("No description"));
        }

        // 启动 Actix-web 服务器
        HttpServer::new(move || {
            App::new()
                .wrap(actix_web::middleware::Logger::default())
                .service(
                    web::scope("/api")
                        .service(get_users)
                        .service(get_user_by_id)
                        .service(create_user)
                        .service(health_check)
                )
        })
        .bind("127.0.0.1:8080")?
        .run()
        .await
    }
}

#[cfg(not(feature = "actix"))]
fn main() {
    println!("This example requires the 'actix' feature to be enabled.");
    println!("Run with: cargo run --example actix_example --features actix");
}

#[cfg(feature = "actix")]
fn main() {
    actix_impl::main();
}